<?php
/**
 * 用户列表
 *
 */
function li($page_size = ADM_PAGESIZE) {
    global $_TABLES;

    $view_var   = array();
    $tbl_main   = $_TABLES['admin_roles'];
    $where      = 'WHERE 1 ';

    $conn   = & get_db_conn();


    // 分页处理开始
    $csql   = "SELECT COUNT(*) AS rs_count FROM $tbl_main $where";
    $rs     = $conn->GetRow($csql);



    $record_total   = @(int)$rs['rs_count'];
    $page_total     = ceil($record_total/$page_size);

    $page   = @(int)$_GET['page'];
    if($page > $page_total) $page = $page_total;
    if($page < 1) $page = 1;

    $view_var['record_total']   = $record_total;
    $view_var['page_total']     = $page_total;
    $view_var['page']           = $page;
    $view_var['page_size']      = $page_size;
    // 分页处理完毕


    // 列表处理开始
    $order_by   = trim(@$_GET['orderby']);
    $order_desc = @(int)$_GET['desc'];

    $str_order_by   = '';
    if($order_by != '') {
        $order_desc = ($order_desc!=1)?'ASC':'DESC';
        $str_order_by = "`{$order_by}` {$order_desc}, ";
    }

    $sql    = "SELECT * FROM $tbl_main
            $where 
            ORDER BY  $str_order_by uid DESC ";

    $rs = $conn->PageExecute($sql,$page_size,$page);
    $view_var['record'] = $rs->GetRows();

    return $view_var;
}


function read($id = 0) {
    global $_TABLES, $timestamp;

    $view_var   = array();
    $tbl_main   = $_TABLES['admin_roles'];
    if($id > 0) {
        $conn   = & get_db_conn();
        $sql    = "SELECT * FROM $tbl_main WHERE id = $id ";
        $view_var   = $conn->GetRow($sql);
    } else {
        $view_var   = array(
            'id'    => 0,
            'rolename'  => '',
            'description'   => '',
            );
    }
    return $view_var;
}


function syn_roles($curop, $id) {
    global $_TABLES;
    $tbl_main   = $_TABLES['admin_roles_op'];
    $conn   = & get_db_conn();

    // 得到$id下有多少操作，
    // 
    $sql    = "SELECT * FROM $tbl_main WHERE roleid = $id ";
    $op = $conn->Execute($sql);
    $op = $op->GetRows();

    // 分析当前操作
    foreach($curop as $rightvar => $varvalue) {
        // 看当前数据库中是否存在这个 $rightvar\
        $find = false;
        foreach($op as $dbop) {
            if($dbop['rightvar'] == $rightvar) {
                $find = true;
                break;
            }
        }

        // $curvarvalue = $varvalue 中循环取或
        $curvarvalue = 0;
        foreach($varvalue as $cv) {
            $cv = @(int)$cv;
            $curvarvalue = ($curvarvalue | $cv);
        }

        if($find) {
            // 找到了。需要修改，
            $msql   = "UPDATE $tbl_main SET varvalue = '$curvarvalue' WHERE roleid = '$id' AND rightvar = '$rightvar' ";
            $conn->Execute($msql);
        } else {
            // 没有找到，需要增加，
            $isql   = "INSERT INTO $tbl_main (roleid, rightvar, varvalue) VALUES ('$id', '$rightvar', '$curvarvalue') ";
            $conn->Execute($isql);
        }
    }

    // 删除原来有的，但是现在没有的
    foreach($op as $dbop) {
        // 看现在的值还有没有，
        $find = false;
        foreach($curop as $rightvar => $varvalue) {
            if($rightvar == $dbop['rightvar']) {
                $find   = true;
                break;
            }
        }
        if(!$find) {
            $dsql   = "DELETE FROM $tbl_main WHERE roleid = '$id' AND rightvar = '" . $dbop['rightvar'] . "' ";
            $conn->Execute($dsql);
        }
    }
    // 等下来优化
}





function request() {
    global $action;
    $data = $_POST['role'];
    
    if(!empty($_POST['roles_op']) && is_array($_POST['roles_op']) && sizeof($_POST['roles_op']) > 0) {
        $data['roles_op']   = $_POST['roles_op'];
    } else {
        // 防止开全报错时出错
        $data['roles_op']   = array();
    }


    $rule   = array(
        'rolename'  => 'i_string|len:1:50', 
        );
    $def_err= array(
        'rolename'  => '“角色名称”必须填写，且长度必须在1～50个字符之间！', 
        );

    $result = data_validator($data, $rule, $def_err);
    if($result === true) {
    } else {
        foreach($result as $v) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                        $v, 
                        __FILE__,
                        __LINE__);
        }
    }

    if($GLOBALS['ERR']->Count > 0) {
        return false;
    } else {
        return $data;
    }
}

function add() {
    global $_TABLES, $timestamp;
    $tbl_main   = $_TABLES['admin_roles'];

    $result = request();
    if($result !== false) {
        $conn   = & get_db_conn();

        // 先查看是否有同名用户
        $sql = "SELECT COUNT(*) AS rs_count FROM $tbl_main WHERE rolename = '{$result['rolename']}' ";
        $rs = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '系统中已经存在角色名为<FONT COLOR=\"red\">' . $result['rolename'] . '</FONT>的角色，无法当前添加操作！', 
                __FILE__,
                __LINE__);
        } else {
            $conn->AutoExecute($tbl_main,$result,'INSERT');
            $id = $conn->Insert_ID();
            syn_roles($result['roles_op'], $id);
            return $id;
        }
    }
    return false;
}

function modify() {
    global $_TABLES, $timestamp;
    $tbl_main   = $_TABLES['admin_roles'];

    $result = request();
    if($result !== false) {
        $conn   = & get_db_conn();

        // 先查看是否有同名用户
        $sql = "SELECT COUNT(*) AS rs_count FROM $tbl_main WHERE rolename = '{$result['rolename']}' AND id <> '{$result['id']}' ";
        $rs = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '系统中已经存在角色名为<FONT COLOR=\"red\">' . $result['rolename'] . '</FONT>的角色，无法完成当前修改操作！', 
                __FILE__,
                __LINE__);
        } else {
            $conn->AutoExecute($tbl_main,$result,'UPDATE','id=' . $result['id'] . '');
            syn_roles($result['roles_op'], $result['id']);
            return $result['id'];
        }
    }
    return false;
}

function del() {
    global $_TABLES;
    $tbl_main   = $_TABLES['admin_roles'];

    $deltype    = @$_POST['deltype'];
    if($deltype == 'all') {
        // 删除POST传递过来的 item_id 
        // 批量删除
        $item_id= $_POST['item_id'];
        $str_in = '';
        if(is_array($item_id) && sizeof($item_id) > 0) {
            foreach($item_id as $v) {
                $v  = @(int)$v;
                $str_in .= ($str_in == '')?"{$v}":",{$v}";
            }
        } else {
            $item_id = @(int)$item_id;
            if($item_id > 0) $str_in = $item_id;
        }
    } else {
        // get传递过来的删除 单条删除
        $item_id= @(int)$_GET['item_id'];
        $str_in = $item_id;
    }

    if($str_in != '') {
        $conn   = & get_db_conn();
        $sql    = "DELETE FROM $tbl_main WHERE id IN ({$str_in}) ";
        if($conn->Execute($sql)) {
            js_success('删除指定角色成功！');
        }
    }
}




function modules_actions($id) {
    global $G_cfg, $_TABLES;
    $tbl_main   = $_TABLES['admin_roles_op'];
    $conn   = & get_db_conn();

    // 得到$id下有多少操作，
    // 
    $sql    = "SELECT * FROM $tbl_main WHERE roleid = $id ";
    $op = $conn->Execute($sql);
    $op = $op->GetRows();


    // 遍历admin/modules 下的所有文件夹，找到mod.conf.php并处理
    $modpath    = realpath(dirname(__FILE__) . '/../');
    if ($dh = opendir($modpath)) {
        while (($file = readdir($dh)) !== false) {
            if($file != '.' && $file != '..') {
                $conffile   = $modpath . '/' . $file . '/mod.conf.php';
                if(file_exists($conffile) && is_file($conffile)) {
                    
                    require($conffile);
                }
            }
        }
        closedir($dh);
    }


    
    $str    = '';
    foreach($GLOBALS['_MODULES'] as $module => $detail) {
        // 找下面的子模块
        $str_mod    = '';
        foreach($detail['submod'] as $subprefix => $submod) {
            $find = false;
            $dbopv = 0;
            foreach($op as $dbop) {
                if($submod['right_var'] == $dbop['rightvar']) {
                    $dbopv  = @(int)$dbop['varvalue'];
                    $find = true;
                    break;
                }
            }


            $str_submod = '';
            $subid  = $submod['right_var'];
            foreach($detail['actions'] as $action => $adetail) {
                $checked    = '';
                if($find && (@(int)$adetail['code'] & $dbopv)==@(int)$adetail['code']) {
                    // 如果
                    $checked    = 'checked';
                }





                if(($subprefix=='' && strpos($action, '.')===false) || 
                   ($subprefix!='' && substr($action, 0, (strlen($subprefix)+1)) == $subprefix.'.')
                  ) {
                    $chkid      = $submod['right_var'] . '_' . $action;
                    $str_submod .= '<INPUT TYPE="checkbox" ID="'.$chkid.'" NAME="roles_op[' . 
                        $submod['right_var']
                    . '][' . $action . ']" VALUE="' . $adetail['code'] . '" ' . $checked . '> ' .
                      '<label for="' . $chkid . '">' .  $adetail['name'] . '</label>';
                }
            }

            $str_mod   .= "<TABLE border=\"0\" width=\"100%\" cellpadding=\"2\" cellspacing=\"2\" style=\"margin:5px 0px 0px 30px\">
            <TR>
                <!-- <TD> <INPUT TYPE=\"checkbox\" ID=\"$subid\" NAME=\"\" value=\"\"> <label for=\"$subid\"><B>{$submod['name']}</B></label></TD> -->
                <TD> <B>{$submod['name']}</B> </TD>
            </TR>
            <TR>
                <TD>{$str_submod}</TD>
            </TR>
            </TABLE>";
        }


        $str   .= "<TABLE border=\"0\" width=\"100%\" class=\"bordertable01\">
        <TR>
            <TD style=\"font-size:14px;font-weight:bold;background-color:#DEEFFA\">&nbsp;&nbsp;{$detail['name']}</TD>
        </TR>
        <TR>
            <TD>$str_mod</TD>
        </TR>
        </TABLE>";

    }
    return $str;
}

?>